package com.madeinsolitary.control;

import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.madeinsolitary.service.UserService;


@Controller
@RequestMapping("user")
public class User {
	@Autowired
	private UserService userService;
	
	
	@RequestMapping(value="/register.do",method=RequestMethod.POST)
	@ResponseBody 
	public void addUserInfo(HttpServletRequest request,HttpServletResponse response) throws Exception{
		Map<String,Object> paramMap = new HashMap<String,Object>();
		Enumeration<String> pNames = request.getParameterNames();
		while(pNames.hasMoreElements()){
			String pName =pNames.nextElement();
			
			paramMap.put(pName, request.getParameter(pName));
		}
		//获得用户IP
		String ip = "";
		if (request.getHeader("x-forwarded-for") == null) {
			ip =  request.getRemoteAddr();
		} else {
			ip = request.getHeader("x-forwarded-for");
		}
		System.out.println(ip);
		paramMap.put("ip", ip);
		Date now = new Date();
		paramMap.put("register_date", now);
		paramMap.put("last_login_date", now);
		userService.addUserInfo(paramMap);
	}
	
	@RequestMapping(value="/login.do",method=RequestMethod.POST)
	@ResponseBody 
	public Map<String,Object> verifyUserInfo(HttpServletRequest request,HttpServletResponse response) throws Exception{
		Map<String,Object> paramMap = new HashMap<String,Object>();
		Map<String,Object> respMap = new HashMap<String,Object>();
		Enumeration<String> pNames = request.getParameterNames();
		while(pNames.hasMoreElements()){
			String pName =pNames.nextElement();			
			paramMap.put(pName, request.getParameter(pName));
		}
		//获得用户IP
		String ip = "";
		if (request.getHeader("x-forwarded-for") == null) {
			ip =  request.getRemoteAddr();
		} else {
			ip = request.getHeader("x-forwarded-for");
		}
		paramMap.put("ip", ip);
		Date now = new Date();
		paramMap.put("last_login_date", now);
		boolean success = false;
		if(userService.verifyUserInfo(paramMap)) {
			success = true;
		}
		respMap.put("success", success);
		return respMap;
	}
	
}
